package serviceapi

import (
	_ "iot-base/common/ctrl"
	"iot-base/common/ctrltype"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"iot-base/common/webapi"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

const CTRLERROR = -1

func runCtrl(ntimeout int, cmd *ctrltype.CtrlCmd, uid string, c *gin.Context) {
	var timeoutDuration time.Duration = time.Duration(ntimeout) * time.Second
	var pResult *ctrltype.CtrlResult
	notify.Ctrl(cmd, timeoutDuration, func(pReply *ctrltype.CtrlResult) {
		pResult = pReply

	}, true)
	if pResult == nil {
		return
	}
	if pResult.Error != nil && pResult.Error.Error() == "time out" {
		logger.SLog.Error("error-------runctrl", "cmd", cmd, "result", pResult.Error)
	} else {
		if pResult.Error != nil {
			webapi.SendError(pResult.Error.Error(), CTRLERROR, c)
		} else {
			webapi.SendResult(pResult, nil, c)
		}

	}
}

func InitService(api *gin.RouterGroup) {
	service := api.Group("service")
	{

		service.PUT("/", func(c *gin.Context) {

			uid := c.Query("uid")
			if uid == "" {
				webapi.SendError("uid is empty", webapi.ParamMissed, c)
				return
			}
			var ntimeout int = 0
			timeout := c.Query("timeout")
			if timeout == "" || timeout == "0" {
				ntimeout = 10
			} else {
				ntimeout, _ = strconv.Atoi(timeout)
			}
			var cmd ctrltype.CtrlCmd
			c.BindJSON(&cmd)
			/*
					ctx, cancel := context.WithTimeout(c.Request.Context(), time.Duration(ntimeout)*time.Second)
					defer func() {
						// check if context timeout was reached
						if ctx.Err() == context.DeadlineExceeded {

							// write response and abort the request
							c.Writer.WriteHeader(http.StatusGatewayTimeout)
							c.Abort()
							cancel()
						}

						//cancel to clear resources after finished

					}()

				defer func() {
					//设置recover拦截错误信息
					err := recover()
					//产⽣panic异常 打印错误信息
					if err != nil {
						var buf [4096]byte
						n := runtime.Stack(buf[:], false)
						logger.SLog.Error("error-------runctrl", "cmd", cmd, "stack", string(buf[:n]))
					}
				}()*/

			//copyContext := c.Copy()
			runCtrl(ntimeout, &cmd, uid, c)

		})

	}

}
